package cc.rboot.permission.holder;

import cc.rboot.permission.core.IResourcePermission;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * FIXME: 性能不高，有时间再改
 */
@Component
public class ResourcePermissionHolder {

    @Resource
    List<IResourcePermission> resourcePermissionList;

    /**
     * 获取当前用户的所有rp角色
     * @return
     */
    public List<IResourcePermission> present() {
        return resourcePermissionList.stream()
                .filter(IResourcePermission::has)
                .collect(Collectors.toList());
    }

    /**
     * 确认当前用户是否拥有指定的角色
     * @param permissionClass
     * @return
     */
    public boolean has(Class<? extends IResourcePermission> permissionClass) {
        return this.present().stream().anyMatch(permission -> permission.getClass() == permissionClass);
    }

    /**
     * 确认当前用户是否拥有指定的角色
     * @param permissionName
     * @return
     */
    public boolean has(String permissionName) {
        return this.present().stream()
                .anyMatch(permission -> permissionName.equals(permission.name()));
    }

    /**
     * 获取指定角色的bean
     * @param permissionClass
     * @return
     */
    public IResourcePermission get(Class<? extends IResourcePermission> permissionClass) {
        return resourcePermissionList.stream()
                .filter(permission -> permission.getClass() == permissionClass)
                .findFirst().get();
    }

    /**
     * 获取指定角色的bean
     * @param permissionName
     * @return
     */
    public IResourcePermission get(String permissionName) {
        return resourcePermissionList.stream()
                .filter(permission -> permissionName.equals(permission.name()))
                .findFirst().get();
    }

}